package com.controller;

import com.entity.Blog;
import com.entity.Page;
import com.service.impl.BlogServiceImpl;
import com.service.intf.BlogService;
import com.utils.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

public class BlogServlet extends BaseServlet {
    private  BlogService blogService = new BlogServiceImpl();
//    FavourService favourService =new FavourServiceImpl();
    /**
     * 查询用户的所有博客文章
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void queryBlog(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String username = req.getParameter("username");  //当前用户名
        Integer userId = blogService.queryUserIdByUserName(username);
        req.getSession().setAttribute("userId",userId);
        List<Blog> blogs = blogService.queryBlogByUserName(username);
        req.setAttribute("blogs", blogs);
        //想要查询到的用户
        String  queryUserName = (String) req.getParameter("queryUserName");

        req.getSession().setAttribute("queryUserName",queryUserName);
//        Integer queryUserId = req.getParameter("queryUserId");

//        String  queryUserName = (String) req.getSession().getAttribute("queryUserName")==null?"":(String) req.getSession().getAttribute("queryUserName");
        //此处是为了区分是用户本人点进博客主页，还是另外的人点进用户主页
        //如果是用户自己点进博客主页，就会显示删除，修改博客等功能
        //如果不是，则不会显示删除，修改博客等功能
        if(queryUserName!=null){   //说明有查询
            if(username.equals(queryUserName)){     //查到用户自己
                req.getSession().setAttribute("self",true);
//                req.getSession().setAttribute("queryUserName",queryUserName);

            }else {//查到别的用户
                req.getSession().setAttribute("self",false);
                //查询想要查询的用户的博客文章
                blogs = blogService.queryBlogByUserName(queryUserName);
//                req.getSession().setAttribute("queryUserName",queryUserName);
                req.setAttribute("blogs", blogs);
            }
        }else { //说明没有查询
//            req.getSession().setAttribute("queryUserName",queryUserName);
            req.getSession().setAttribute("self",true);
        }



        req.getRequestDispatcher("/pages/blog/blog_list.jsp").forward(req, resp);
//        resp.sendRedirect(req.getContextPath()+"relationServlet?action=queryFollower&username="+username);

    }


//    protected void queryUserName(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//
//    }

        /**
         * 详细查看某一篇博客文章
         * @param req
         * @param resp
         * @throws ServletException
         * @throws IOException
         */
    protected void querySingleBlog(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Integer blogId = WebUtils.parseInt(req.getParameter("blogId"), 0);
//        String username = (String) req.getSession().getAttribute("username");
        req.getSession().setAttribute("blogId",blogId);
        Blog blog = blogService.querySingleBlogByBlogId(blogId);
        req.getSession().setAttribute("blog", blog);

        int queryUserId = WebUtils.parseInt(req.getParameter("queryUserId"), 0);
        String  queryUserName = blogService.queryUserNameByUserId(queryUserId);
        if(queryUserId>0){   //证明用户想要查询某一篇博客，需要显现出这个博客作者的信息
            queryUserName = blogService.queryUserNameByUserId(queryUserId);
            req.getSession().setAttribute("queryUserName",queryUserName);
        }

//        然后跳转到FavourServlet去查询具体的点赞数！
        resp.sendRedirect(req.getContextPath()+"/user/favourServlet?action=queryFavourByBlogId&blogId="+blogId);


//        req.getRequestDispatcher("/pages/blog/blog_detail.jsp").forward(req, resp);


    }

    /**
     * 通过博客文章的id来删除博客
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void deleteBlogByBlogId(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Integer blogId = WebUtils.parseInt(req.getParameter("blogId"), 0);
//        Integer blogId = Integer.valueOf(req.getParameter("blogId"));
        blogService.deleteBlogByBlogId(blogId);
        resp.sendRedirect(req.getContextPath()+"/blogServlet?action=page&username="+req.getParameter("username")+"&pageNo="+req.getParameter("pageNo"));

    }


    /**
     * 通过博客文章的id来修改博客
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void updateBlog(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String userName=req.getParameter("userName");
        //获取到指定那一篇博客的id
        Integer blogId = WebUtils.parseInt(req.getParameter("blogId"), 0);


        req.getSession().setAttribute("blogId",blogId);
        //获取修改后的博客内容
        String  content = req.getParameter("content");
//        String userName = ;
        //证明只是在blog_list.jsp（我的个人主页）点开了修改文章按钮，并没有真正修改文章内容
        if(content==null||"".equals(content)){

            //获取到对应的博客
            Blog blog = blogService.querySingleBlogByBlogId(blogId);

//            Integer userId = blog.getUserId();


            //获取到对应的博客内容可以让他在blog_update.jsp显示出来
            String content1=blog.getContent();

            //用于回显原本的博客内容
            req.getSession().setAttribute("content1", content1);

            req.getRequestDispatcher("/pages/blog/blog_update.jsp").forward(req, resp);

        }else {    //证明已经在blog_update.jsp并提交了修改博客内容


            blogService.updateBlog(content,blogId);
            //重定向到用户个人主页
            resp.sendRedirect(req.getContextPath()+"/blogServlet?action=page&username="+req.getParameter("userName")+"&pageNo="+req.getParameter("pageNo"));


        }
    }

    /**
     * 增加博客文章
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void addBlog(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取请求参数
        String userName = req.getParameter("userName");
        String  content = req.getParameter("content");
        int pageNo = WebUtils.parseInt(req.getParameter("pageNo"), 0);
        pageNo+=1;
        //获取对应用户的id
        Integer userId= (Integer) req.getSession().getAttribute("userId");
        //增加博客文章
        blogService.addBlog(content,userId);
        //重定向到用户个人主页
        resp.sendRedirect(req.getContextPath()+"/blogServlet?action=page&username="+req.getParameter("userName")+"&pageNo="+pageNo);


    }

    /**
     * 处理分页功能
     * @param req
     * @param resp
     * @throws Exception
     */
    protected void page(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        //1 获取请求的参数 pageNo,pageSize ,userId

        //第一次点进图书管理，pageNo为空（因为request域中都没设置page对象），所以默认值1赋值给pageNo
        int pageNo = WebUtils.parseInt(req.getParameter("pageNo"), 1);
        int pageSize = WebUtils.parseInt(req.getParameter("pageSize"), Page.PAGE_SIZE);
        String username = req.getParameter("username");
        Integer userId= blogService.queryUserIdByUserName(username);
        req.getSession().setAttribute("userId",userId);

        //想要查询到的用户
        String  queryUserName = (String) req.getParameter("queryUserName");
        if(queryUserName!=null){

            req.getSession().setAttribute("queryUserName",queryUserName);
        }
//        else {
//            queryUserName= (String) req.getSession().getAttribute("queryUserName");
//        }


        //判断当前页面是不是用户自己的博客主页，false代表不是，true代表是
        Boolean self=false;
        //2 调用 BlogService.page(pageNo，pageSize)：Page 对象


        Page<Blog> page = blogService.page(pageNo,pageSize,userId);
        page.setUrl("blogServlet?action=page");
        //3 保存 Page 对象到 Session 域中
        req.getSession().setAttribute("page",page);
//        page.setUrl("manager/bookServlet?action=page");

        //此处是为了区分是用户本人点进博客主页，还是另外的人点进用户主页
        //如果是用户自己点进博客主页，就会显示删除，修改博客等功能
        //如果不是，则不会显示删除，修改博客等功能
        if(queryUserName!=null){   //说明有查询
            if(username.equals(queryUserName)){     //查到用户自己
                self=true;
//                req.getSession().setAttribute("queryUserName",queryUserName);

            }else {//查到别的用户
                userId=blogService.queryUserIdByUserName(queryUserName);
                //查询想要查询的用户的博客文章
                page = blogService.page(pageNo,pageSize,userId);
//                req.getSession().setAttribute("queryUserName",queryUserName);
                page.setUrl("blogServlet?action=page");
                req.getSession().setAttribute("page", page);
            }
        }else { //说明没有查询
            self=true;
//            req.getSession().setAttribute("queryUserName",queryUserName);

        }
        System.out.println(req.getHeader("referer"));
        System.out.println(req.getQueryString());
        String getQueryString= req.getQueryString();
        System.out.println(getQueryString);

        if(queryUserName!=null){

            if(getQueryString.contains(queryUserName)){
                System.out.println("关于cjr12");
            }
        } else if(getQueryString.contains(username)){
            System.out.println("关于本用户admin");
        }

        System.out.println("self"+self);
        req.getSession().setAttribute("self",self);
//        if(self==true){
            //4 请求转发到pages/blog/blog_list.jsp 页面
            req.getRequestDispatcher("/pages/blog/blog_list.jsp").forward(req,resp);

//        }else {
//            req.getRequestDispatcher("/pages/blog/queryUserBlog_list.jsp").forward(req,resp);
//
//        }


    }
}